package com.bwie.redkids;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Xml;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.bwie.redkids.bean.CartBean;
import com.bwie.redkids.bean.UpdateBean;
import com.bwie.redkids.fragment.BrandFragment;
import com.bwie.redkids.fragment.HomeFragment;
import com.bwie.redkids.fragment.MoreFragment;
import com.bwie.redkids.fragment.SearchFragment;
import com.bwie.redkids.fragment.ShoppingFragment;
import com.bwie.redkids.fragment.ShoppingsFragment;
import com.bwie.redkids.utils.CartDBUtils;
import com.gblw.util.UpdateVersionUtil;

public class IndexActivity extends BaseActivity implements OnClickListener {

	private RadioButton rb_index_more;
	private RadioButton rb_index_shopping;
	private RadioButton rb_index_brand;
	private RadioButton rb_index_search;
	private RadioButton rb_index_home;
	private LinearLayout lin_index;
	private FragmentManager manager;
	private FragmentTransaction transaction;
	private FragmentTransaction beginTransaction;
	private static final int SUCESS = 0;
	private Button bt_update;
	private ArrayList<UpdateBean> updateBeanList;
	private UpdateBean updateBean;
	private CartDBUtils cartDBUtils = new CartDBUtils();
	UpdateBean upDateVersion;

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 0) {
				UpdateBean bean = (UpdateBean) msg.obj;
				// System.out.println(UpdateBean.getDownloadUrl()
				// + "-----------------------------");
				UpdateVersionUtil updataManger = UpdateVersionUtil
						.getUpdataManger(bean.getDownloadUrl(),
								IndexActivity.this, bean.getVersionName(),
								bean.getUpdateLog());

				updataManger.checkUpdata();

			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_index);
		cartDBUtils.openSQLite(this);
		initView();
		getFragment();
		getData();
	}

	/**
	 * 初始化数据
	 * */
	private void initView() {
		lin_index = (LinearLayout) findViewById(R.id.lin_index);
		rb_index_home = (RadioButton) findViewById(R.id.rb_index_home);
		rb_index_search = (RadioButton) findViewById(R.id.rb_index_search);
		rb_index_brand = (RadioButton) findViewById(R.id.rb_index_brand);
		rb_index_shopping = (RadioButton) findViewById(R.id.rb_index_shopping);
		rb_index_more = (RadioButton) findViewById(R.id.rb_index_more);

		rb_index_home.setOnClickListener(this);
		rb_index_search.setOnClickListener(this);
		rb_index_brand.setOnClickListener(this);
		rb_index_shopping.setOnClickListener(this);
		rb_index_more.setOnClickListener(this);
	}

	/**
	 * 刚开始进入时添加fragment
	 * */
	private void getFragment() {
		manager = getSupportFragmentManager();
		transaction = manager.beginTransaction();
		transaction.add(R.id.lin_index, new HomeFragment(), "home");
		transaction.commit();
	}

	@Override
	public void onClick(View v) {
		beginTransaction = manager.beginTransaction();
		switch (v.getId()) {
		case R.id.rb_index_home:
			if (manager.findFragmentByTag("home") != null) {
				beginTransaction.replace(R.id.lin_index,
						manager.findFragmentByTag("home"));
			} else {
				beginTransaction.replace(R.id.lin_index, new HomeFragment(),
						"home");
			}
			break;
		case R.id.rb_index_search:
			if (manager.findFragmentByTag("search") != null) {
				beginTransaction.replace(R.id.lin_index,
						manager.findFragmentByTag("search"));
			} else {
				beginTransaction.replace(R.id.lin_index, new SearchFragment(),
						"search");
			}

			break;
		case R.id.rb_index_brand:
			if (manager.findFragmentByTag("brand") != null) {
				beginTransaction.replace(R.id.lin_index,
						manager.findFragmentByTag("brand"));
			} else {
				beginTransaction.replace(R.id.lin_index, new BrandFragment(),
						"brand");
			}
			break;
		case R.id.rb_index_shopping:
			ArrayList<CartBean> query = cartDBUtils.query();
			if (query == null) {
				if (manager.findFragmentByTag("shoppiing") != null) {
					beginTransaction.replace(R.id.lin_index,
							manager.findFragmentByTag("shopping"));
				} else {
					beginTransaction.replace(R.id.lin_index,
							new ShoppingFragment(), "shopping");
				}
			} else {
				if (manager.findFragmentByTag("shoppiings") != null) {
					beginTransaction.replace(R.id.lin_index,
							manager.findFragmentByTag("shoppings"));
				} else {
					beginTransaction.replace(R.id.lin_index,
							new ShoppingsFragment(), "shoppings");
				}
			}

			break;
		case R.id.rb_index_more:
			if (manager.findFragmentByTag("more") != null) {
				beginTransaction.replace(R.id.lin_index,
						manager.findFragmentByTag("more"));
			} else {
				beginTransaction.replace(R.id.lin_index, new MoreFragment(),
						"more");
			}
			break;

		default:
			break;
		}
		beginTransaction.commit();
	}

	private void getData() {
		new Thread() {
			public void run() {
				try {
					URL url = new URL(
							"http://www.oschina.net/MobileAppVersion.xml");
					HttpURLConnection openConnection = (HttpURLConnection) url
							.openConnection();
					openConnection.setConnectTimeout(5000);
					openConnection.setReadTimeout(5000);
					int responseCode = openConnection.getResponseCode();
					if (responseCode == 200) {
						InputStream inputStream = openConnection
								.getInputStream();
						getPull(inputStream);
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}

	protected void getPull(InputStream inputStream) {
		try {
			XmlPullParser newPullParser = Xml.newPullParser();
			newPullParser.setInput(inputStream, "utf-8");

			int eventType = newPullParser.getEventType();
			System.out
					.println("###################################################");

			while (eventType != XmlPullParser.END_DOCUMENT) {

				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					updateBeanList = new ArrayList<UpdateBean>();
					break;
				case XmlPullParser.START_TAG:
					String tagName = newPullParser.getName();

					if ("android".equals(tagName)) {
						updateBean = new UpdateBean();
					} else if ("versionName".equals(tagName)) {
						updateBean.setVersionName(newPullParser.nextText());
					} else if ("downloadUrl".equals(tagName)) {
						updateBean.setDownloadUrl(newPullParser.nextText());

					} else if ("updateLog".equals(tagName)) {
						updateBean.setUpdateLog(newPullParser.nextText());

					}
					break;
				case XmlPullParser.END_TAG:
					String name = newPullParser.getName();
					if (name.equals("android")) {
						updateBeanList.add(updateBean);

					}
					break;
				default:
					break;
				}
				eventType = newPullParser.next();
			}
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		handler.obtainMessage(SUCESS, updateBean).sendToTarget();
	}

}
